#include "sm4_utils.h"
extern "C" {
    #include <gmssl/sm4.h>
}

QByteArray sm4_encrypt(const QByteArray &plain, const QByteArray &key) {
    if (key.size() != 16) return {};

    SM4_KEY sm4_key;
    sm4_set_encrypt_key(&sm4_key, (const uint8_t *)key.constData());

    uint8_t iv[16];
    memcpy(iv, key.constData(), 16);  // 简单用 key 做 IV，或改为随机数

    uint8_t out[8192] = {0};  // 最大 8KB 输出缓存
    size_t outlen = sizeof(out);

    int ret = sm4_cbc_padding_encrypt(
        &sm4_key,
        iv,
        (const uint8_t *)plain.constData(), plain.size(),
        out, &outlen);

    if (ret != 1) return {};
    return QByteArray((const char *)out, outlen);
}

QByteArray sm4_decrypt(const QByteArray &cipher, const QByteArray &key) {
    if (key.size() != 16) return {};

    SM4_KEY sm4_key;
    sm4_set_decrypt_key(&sm4_key, (const uint8_t *)key.constData());

    uint8_t iv[16];
    memcpy(iv, key.constData(), 16);  // 保持加解密一致

    uint8_t out[8192] = {0};
    size_t outlen = sizeof(out);

    int ret = sm4_cbc_padding_decrypt(
        &sm4_key,
        iv,
        (const uint8_t *)cipher.constData(), cipher.size(),
        out, &outlen);

    if (ret != 1) return {};
    return QByteArray((const char *)out, outlen);
}
